package kitread.model;

import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import kitread.util.Downloader;
import kitread.util.TextExtractor;

import com.sun.syndication.feed.synd.SyndEntry;

public class FeedItem {

	private Feed owner;
	private String title;
	private Date publishingDate;
	private String description;
	private URL url;
	private Boolean read;
	
	public FeedItem(Feed owner, SyndEntry entry) {
		this.owner = owner;
		this.title = entry.getTitle().trim();
		this.publishingDate = entry.getPublishedDate();
		this.description = TextExtractor.instance().getText(entry.getDescription().getValue());
		try {
			this.url = new URL(entry.getLink());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		this.read = false;
	}
	
	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}
	
	/**
	 * @return the publishingDate
	 */
	public Date getPublishingDate() {
		return publishingDate;
	}
	
	/**
	 * @return the description
	 */
	public String getDescription() {
		return description;
	}
	
	/**
	 * @return the url
	 */
	public URL getUrl() {
		return url;
	}
	
	/**
	 * @return the read
	 */
	public Boolean getRead() {
		return read;
	}
	
	/**
	 * @param title the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}
	
	/**
	 * @param publishingDate the publishingDate to set
	 */
	public void setPublishingDate(Date publishingDate) {
		this.publishingDate = publishingDate;
	}
	
	/**
	 * @param description the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	
	/**
	 * @param url the url to set
	 */
	public void setUrl(URL url) {
		this.url = url;
	}
	
	/**
	 * @param read the read to set
	 */
	public void setRead(Boolean read) {
		this.read = read;
	}
	
	public BufferedImage getIcon() {
		return owner.getIcon();
	}
	
	public String getPageContent() {
		String page = Downloader.downloadPage(getUrl());
		return TextExtractor.instance().getText(page);
	}
	
	@Override
	public int hashCode() {
		return (title +
				((url == null)? "" : url.toString()) +
				publishingDate.toString()).hashCode();
	}
	
	@Override
	public String toString() {
		String s = title + "\n" +
				publishingDate + "\n" +
				//description + "\n" +
				url.getHost() + " (read: " + read + ")\n";
		return s;
	}
}
